<template>
    <a-select size="small" :disabled="readonly" v-model:value="SelectValue">
        <a-select-option v-for="item in Dict" :key="item.value" :value="item.value">
            {{ item.label }}
        </a-select-option>
    </a-select>
</template>
<script setup>
import { watchEffect, ref, watch, inject } from 'vue';

const emit = defineEmits(['update:modelValue'])
const props = defineProps(['Option', 'modelValue']);

const readonly = ref(false);

watchEffect(() => {
    readonly.value = !!props.Option.readonly
})

const SelectValue = ref();

const GetDict = inject('GetDict')
const UpdateSelectDict = inject('UpdateSelectDict');

watch(() => props.modelValue, val => {
    SelectValue.value = val;
}, { immediate: true });

watch(SelectValue, (val) => {
    emit('update:modelValue', val);
    UpdateSelectDict(props.Option.Key, val);
})

const Dict = ref([]);

if (Array.isArray(props.Option.Dict)) {
    Dict.value = props.Option.Dict;
} else {
    const DictKey = props.Option.Dict.split(':');
    if (DictKey.length == 1) {
        GetDict(DictKey[0]).then(res => {
            Dict.value = res;
        })
    }
}

const GetValueObject = () => {
    var _Object = {};
    for (let i = 0; i < Dict.value.length; i++) {
        const element = Dict.value[i];
        if (element.value == SelectValue.value) {
            _Object = element
            break;
        }
    }
    return _Object;
}

const SetDictValue = (res, value) => {
    Dict.value = res || [];
    SelectValue.value = value;
}

defineExpose({
    GetValueObject,
    SetDictValue
})

</script>
<style lang="less" scoped>

</style>